﻿#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Class.Web.Mvc;
using Telerik.Web.Mvc;
using ThuySan.Bussiness;
using ThuySan.Models;

#endregion

namespace ThuySan.Areas.Backend.Controllers
{
    [Authorize]
    public class CategoryController : BaseController
    {
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();

        #region Category

        public ActionResult Index()
        {
            return View();
        }

        [GridAction]
        public ActionResult GetList()
        {
            return View(new GridModel(_unitOfWork.CategoryRepository.Select().Select(c => new
            {
                c.CategoryId,
                c.Name,
                c.Priority
            })));
        }

        public ActionResult Add()
        {
            return View(new CategoryModel());
        }

        [ValidateInput(false), HttpPost]
        public ActionResult Add(CategoryModel categoryModel)
        {
            if (ModelState.IsValid)
            {
                Category category = categoryModel;
                if (_unitOfWork.CategoryRepository.CheckInsertCategory(category))
                {
                    Exception exception;
                    category.PageUrl = ConvertToUnSign(string.IsNullOrEmpty(categoryModel.PageUrl)
                                                          ? category.Name
                                                          : category.PageUrl);
                    _unitOfWork.CategoryRepository.Insert(category, out exception);
                    if (exception == null)
                    {
                        return RedirectToAction("Index");
                    }
                    ModelState.AddModelError("error", exception.StackTrace);
                }
            }
            return View(categoryModel);
        }

        public ActionResult Edit(string id)
        {
            int guid;
            if (int.TryParse(id, out guid))
            {
                Category category = _unitOfWork.CategoryRepository.Select(c => c.CategoryId == guid).FirstOrDefault();
                if (category != null)
                {
                    CategoryModel categoryModel = category;
                    return View(categoryModel);
                }
            }
            return RedirectToAction("Index");
        }

        [ValidateInput(false), HttpPost]
        public ActionResult Edit(CategoryModel categoryModel)
        {
            if (ModelState.IsValid)
            {
                Category category = _unitOfWork.CategoryRepository.SelectbyId(categoryModel.CategoryId);
                categoryModel.Update(category);
                if (_unitOfWork.CategoryRepository.CheckUpdateCategory(category))
                {
                    Exception exception;
                    category.PageUrl = ConvertToUnSign(string.IsNullOrEmpty(categoryModel.PageUrl)
                                                          ? category.Name
                                                          : category.PageUrl);
                    _unitOfWork.CategoryRepository.Update(category, out exception);
                    if (exception == null)
                    {
                        return RedirectToAction("Index");
                    }
                    ModelState.AddModelError("error", exception.StackTrace);
                }
            }

            return View(categoryModel);
        }

        [HttpPost]
        public ActionResult Delete(string id)
        {
            if (id != null)
            {
                string[] s = id.Split(',');
                int guid;
                List<int> list = (from s1 in s where int.TryParse(s1, out guid) select int.Parse(s1)).ToList();

                if (_unitOfWork.CategoryRepository.CheckDeleteCategory(list))
                {
                    _unitOfWork.CategoryRepository.Delete(list);
                }
            }
            return Content("");
        }

        #endregion

        #region Property

        public ActionResult CategoryProperties(int id)
        {
            ViewBag.Id = id;
            return PartialView();
        }

        [GridAction]
        public ActionResult GetPropertyList(int id)
        {
            return View(new GridModel(_unitOfWork.CategoryPropertyRepository.Select(c => c.CategoryId == id).Select(c => new
            {
                c.CategoryPropertyId,
                c.Property.Name,
                c.Property.GroupName,
                c.Priority,
                IsBit = c.Property.IsBit ?? false
                                ? "checked"
                                : "",
                IsNumber = c.Property.IsNumber ?? false
                                   ? "checked"
                                   : ""
            })));
        }

        public ActionResult AddProperty(int id)
        {
            ViewBag.Properties = _unitOfWork.PropertyRepository.Select().Select(c => new
            {
                c.Name,
                c.PropertyId
            }).ToList().Select(c => new SelectListItem
            {
                Text = c.Name,
                Value = c.PropertyId + ""
            });
            return View(new CategoryPropertyModel
            {
                CategoryId = id
            });
        }

        [ValidateInput(false), HttpPost]
        public ActionResult Addproperty(CategoryPropertyModel categoryPropertyModel)
        {
            if (ModelState.IsValid)
            {
                CategoryProperty categoryProperty = categoryPropertyModel;
                if (_unitOfWork.CategoryPropertyRepository.CheckInsertCategoryProperty(categoryProperty))
                {
                    Exception exception;
                    _unitOfWork.CategoryPropertyRepository.Insert(categoryProperty, out exception);
                    if (exception == null)
                    {
                        ViewBag.Completed = true;
                    }
                }
                else
                {
                    ModelState.AddModelError("PropertyId", "Property has exists.");
                }
            }
            ViewBag.Properties = _unitOfWork.PropertyRepository.Select().Select(c => new
            {
                c.Name,
                c.PropertyId
            }).ToList().Select(c => new SelectListItem
            {
                Text = c.Name,
                Value = c.PropertyId + ""
            });
            return View(categoryPropertyModel);
        }

        [HttpPost]
        public ActionResult DeleteProperty(string id)
        {
            if (id != null)
            {
                string[] s = id.Split(',');
                int guid;
                List<int> list = (from s1 in s where int.TryParse(s1, out guid) select int.Parse(s1)).ToList();

                if (_unitOfWork.CategoryPropertyRepository.CheckDeleteCategoryProperty(list))
                {
                    _unitOfWork.CategoryPropertyRepository.Delete(list);
                }
            }
            return Content("");
        }

        #endregion

        #region Tag

        public ActionResult CategoryTags(int id)
        {
            var ids = _unitOfWork.CategoryTagRepository.Select(c => c.CategoryId == id).Select(c => c.TagId).ToList();
            string first = "";
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var i in ids)
            {
                stringBuilder.AppendFormat("{0}{1}", first, i);
                if (string.IsNullOrEmpty(first))
                    first = ",";
            }
            ViewBag.Ids = stringBuilder.ToString();
            return PartialView(_unitOfWork.TagRepository.Select());
        }

        [HttpPost]
        public ActionResult AddTag(int id, string ids)
        {
            Category category = _unitOfWork.CategoryRepository.Select(c => c.CategoryId == id, "CategoryTags").FirstOrDefault();
            if (category != null)
            {
                while (category.CategoryTags.Count > 0)
                    _unitOfWork.CategoryTagRepository.Delete(category.CategoryTags.First());

                if (!string.IsNullOrEmpty(ids))
                {
                    string[] s = ids.Split(',');
                    int guid;
                    List<int> list = (from s1 in s where int.TryParse(s1, out guid) select int.Parse(s1)).ToList();
                    var tags = _unitOfWork.TagRepository.Select(c => list.Contains(c.TagId));
                    foreach (Tag tag in tags)
                    {
                        category.CategoryTags.Add(new CategoryTag
                                                      {
                                                          Category = category,
                                                          Tag = tag
                                                      });
                    }
                }
                _unitOfWork.AcceptChanges();
            }
            return Content("");
        }

        #endregion

    }
}
